package 线程死锁;

public class ThreadStudy implements Runnable{
    private int flag=1;
    private static Object o1=new Object(),o2=new Object();

    @Override
    public void run() {
        System.out.println("flag="+flag);
        if (flag==1){
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }
        if (flag==0){
            synchronized (o2){
                try {
                    Thread.sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }
                synchronized (o2){
                    System.out.println("0");
                }
            }
        }
    }

    public static void main(String[] args) {
        ThreadStudy ts1 = new ThreadStudy();
        ThreadStudy ts2 = new ThreadStudy();
        ts1.flag=1;
        ts2.flag=0;
        new Thread(ts1).start();
        new Thread(ts2).start();
    }

}
